<template>
  <div class="ai-chat-container" :class="{ 'is-open': isOpen }">
    <!-- 聊天窗口最小化按钮 -->
    <el-tooltip
      content="智能客服"
      placement="left"
      :visible="!isOpen && isTooltipVisible"
      :show-arrow="false"
      effect="dark"
    >
      <div v-if="!isOpen" 
           class="chat-trigger" 
           @click="toggleChat" 
           @mouseenter="isTooltipVisible = true" 
           @mouseleave="isTooltipVisible = false">
        <el-icon><Service /></el-icon>
      </div>
    </el-tooltip>

    <!-- 聊天窗口 -->
    <transition name="el-fade-in-linear">
      <div v-if="isOpen" class="chat-window">
        <!-- 聊天窗口头部 -->
        <div class="chat-header">
          <div class="header-title">
            <el-icon><ChatDotRound /></el-icon>
            <span>智能客服</span>
          </div>
          <div class="header-actions">
            <el-icon @click="toggleChat"><Minus /></el-icon>
          </div>
        </div>

        <!-- 聊天消息区域 -->
        <div class="chat-messages" ref="messageContainer">
          <div v-for="(msg, index) in messages" :key="index" 
               :class="['message', msg.type === 'user' ? 'user-message' : 'ai-message']">
            <div class="message-content" v-html="msg.content"></div>
          </div>
        </div>

        <!-- 输入区域 -->
        <div class="chat-input">
          <el-input
            v-model="userInput"
            placeholder="请输入您的问题..."
            :disabled="loading"
            @keyup.enter="sendMessage"
          >
            <template #append>
              <el-button :loading="loading" @click="sendMessage">发送</el-button>
            </template>
          </el-input>
        </div>
      </div>
    </transition>
  </div>
</template>

<script>
import { ref, onMounted, nextTick, computed } from 'vue'
import request from '@/utils/request'
import { Minus, Service, ChatDotRound } from '@element-plus/icons-vue'

export default {
  name: 'AiChat',
  components: { Minus, Service, ChatDotRound },
  setup() {
    const isOpen = ref(true)
    const isTooltipVisible = ref(false)
    const loading = ref(false)
    const userInput = ref('')
    const messages = ref([
      {
        type: 'ai',
        content: '您好！我是AI智能客服，请问有什么可以帮您？'
      }
    ])
    const messageContainer = ref(null)

    // 处理API响应
    const handleApiResponse = (response) => {
      if (typeof response === 'string') {
        try {
          const jsonResponse = JSON.parse(response)
          if (jsonResponse.code === 200 && jsonResponse.data) {
            return jsonResponse.data
          }
          throw new Error('响应格式错误')
        } catch (e) {
          return response // 如果解析失败，返回原始响应
        }
      } else if (response && response.code === 200 && response.data) {
        return response.data
      }
      throw new Error('响应格式错误')
    }

    // 发送消息
    const sendMessage = async () => {
      if (!userInput.value.trim() || loading.value) return

      // 添加用户消息
      messages.value.push({
        type: 'user',
        content: userInput.value
      })

      loading.value = true
      try {
        // 调用AI对话API
        const response = await request({
          url: '/api/front/ai/chat',
          method: 'post',
          data: {
            message: userInput.value
          }
        })

        // 处理响应并添加AI回复
        const aiMessage = handleApiResponse(response)
        messages.value.push({
          type: 'ai',
          content: aiMessage
        })

        userInput.value = ''
        
        // 滚动到最新消息
        await nextTick()
        scrollToBottom()
      } catch (error) {
        console.error('发送消息失败:', error)
        messages.value.push({
          type: 'ai',
          content: '抱歉，我遇到了一些问题，请稍后再试。'
        })
      } finally {
        loading.value = false
      }
    }

    // 切换聊天窗口
    const toggleChat = () => {
      isOpen.value = !isOpen.value
      if (isOpen.value) {
        nextTick(() => {
          scrollToBottom()
        })
      }
    }

    // 滚动到底部
    const scrollToBottom = () => {
      if (messageContainer.value) {
        messageContainer.value.scrollTop = messageContainer.value.scrollHeight
      }
    }

    return {
      isOpen,
      isTooltipVisible,
      loading,
      userInput,
      messages,
      messageContainer,
      sendMessage,
      toggleChat
    }
  }
}
</script>

<style scoped>
.ai-chat-container {
  position: fixed;
  right: 30px;
  bottom: 30px;
  z-index: 9999;
}

.chat-trigger {
  position: absolute;
  right: 0;
  bottom: 0;
  background: #5e5ce6;
  color: white;
  width: 56px;
  height: 56px;
  border-radius: 28px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 8px 24px rgba(94, 92, 230, 0.3);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  border: none;
  z-index: 10000;
}

.chat-trigger:hover {
  transform: translateY(-2px);
  box-shadow: 0 12px 32px rgba(94, 92, 230, 0.4);
}

.chat-window {
  position: absolute;
  right: 0;
  bottom: 80px;
  width: 360px;
  height: 560px;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(20px);
  -webkit-backdrop-filter: blur(20px);
  border-radius: 24px;
  box-shadow: 0 12px 40px rgba(0, 0, 0, 0.12);
  display: flex;
  flex-direction: column;
  overflow: hidden;
  border: 1px solid rgba(0, 0, 0, 0.1);
}

.chat-header {
  padding: 20px;
  background: rgba(255, 255, 255, 0.8);
  backdrop-filter: blur(12px);
  -webkit-backdrop-filter: blur(12px);
  border-bottom: 1px solid rgba(0, 0, 0, 0.1);
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: 500;
  color: #1d1d1f;
}

.header-title .el-icon {
  font-size: 20px;
  color: #5e5ce6;
}

.header-actions .el-icon {
  cursor: pointer;
  padding: 8px;
  border-radius: 50%;
  color: #86868b;
  transition: all 0.2s ease;
}

.header-actions .el-icon:hover {
  background: rgba(0, 0, 0, 0.05);
  color: #1d1d1f;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.chat-messages::-webkit-scrollbar {
  width: 8px;
}

.chat-messages::-webkit-scrollbar-track {
  background: transparent;
}

.chat-messages::-webkit-scrollbar-thumb {
  background: rgba(0, 0, 0, 0.1);
  border-radius: 4px;
}

.message {
  max-width: 85%;
  padding: 12px 16px;
  border-radius: 16px;
  font-size: 14px;
  line-height: 1.5;
}

.user-message {
  align-self: flex-end;
  background: #5e5ce6;
  color: white;
  border-bottom-right-radius: 4px;
}

.ai-message {
  align-self: flex-start;
  background: #f5f5f7;
  color: #1d1d1f;
  border-bottom-left-radius: 4px;
}

.chat-input {
  padding: 16px;
  background: rgba(255, 255, 255, 0.8);
  backdrop-filter: blur(12px);
  -webkit-backdrop-filter: blur(12px);
  border-top: 1px solid rgba(0, 0, 0, 0.1);
}

.chat-input :deep(.el-input__wrapper) {
  background: rgba(0, 0, 0, 0.03);
  border: none;
  box-shadow: none !important;
  border-radius: 12px;
}

.chat-input :deep(.el-input__wrapper:hover),
.chat-input :deep(.el-input__wrapper.is-focus) {
  background: rgba(0, 0, 0, 0.05);
}

.chat-input :deep(.el-input-group__append) {
  background: transparent;
  border: none;
  padding: 0 0 0 8px;
}

.chat-input :deep(.el-button) {
  background: #5e5ce6;
  border-color: #5e5ce6;
  border-radius: 12px;
  padding: 8px 16px;
  font-weight: 500;
}

.chat-input :deep(.el-button:hover) {
  background: #6b69e3;
  border-color: #6b69e3;
}

.chat-input :deep(.el-button.is-loading) {
  background: #5e5ce6;
  border-color: #5e5ce6;
  opacity: 0.8;
}

/* 过渡动画 */
.el-fade-in-linear-enter-active,
.el-fade-in-linear-leave-active {
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.el-fade-in-linear-enter-from,
.el-fade-in-linear-leave-to {
  opacity: 0;
  transform: translateY(20px);
}
</style> 